<script lang="ts" setup>
  import appStore from '@/store'
  import Monitor from '@/api/Monitor'
  import MeSearch from '@/components/Search.vue'
  import { useRouter } from 'vue-router'
  import { timeFormatUTC } from '@/utils/formatter'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { computed, reactive, ref } from 'vue'
  const emit = defineEmits(['fupdate'])
  const router = useRouter()
  const props = defineProps({
    data: Array
  })
  let userType = ref()
  userType.value = localStorage.getItem('UserType') as string
  let searchArr: Array<{ [key: string]: string }> = reactive([])
  let searchData = computed(() => {
    return {
      inputSearch: {
        fleet_id: { name: 'fleet id' },
        fleet_name: { name: 'fleet名称' }
      },
      choseSearch: {
        state: {
          name: '状态',
          num: 0,
          data: [
            { value: 'ERROR', text: 'ERROR' },
            { value: 'ACTIVE', text: 'ACTIVE' },
            { value: 'CREATING', text: 'CREATING' },
            { value: 'DELETING', text: 'DELETING' }
          ]
        }
      }
    }
  })

  const ys = {
    fleet_id: 'fleet id',
    fleet_name: 'fleet 名称',
    state: '状态'
  }
  const setSearchArr = (arr: Array<{ [key: string]: string }>) => {
    searchArr.length = 0
    searchArr.push(...arr)
    let obj: { [key: string]: string } = {}
    searchArr.forEach((item) => {
      let temp_arr = item.value.split(';')
      let value_arr: (string | number)[] = []
      temp_arr.forEach((val) => {
        if (val === '是') {
          value_arr.push(1)
        } else if (val === '否') {
          value_arr.push(0)
        } else {
          value_arr.push(val)
        }
      })
      obj[item.key] = value_arr.join(';')
    })
    emit('fupdate', obj)
  }
  const param = reactive({
    project_id: appStore.userStore.project_id,
    offset: 0,
    limit: 10,
    fleet_id: '',
    url: ''
  })
  const toDetails = (id: string, name: string) => {
    router.push({ name: 'fleetDetails', params: { id, name } })
  }
  const deleteFleet = (fleet_id: string, fleet_name: string) => {
    ElMessageBox.confirm(`确认删除此条数据？\n名称: ${fleet_name}\nFleetID: ${fleet_id} `, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        param.fleet_id = fleet_id
        let res = await Monitor.deleteFleet(param)
        if (res.status < 300) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          emit('fupdate')
        } else {
          ElMessage({
            type: 'info',
            message: '删除失败'
          })
        }
      })
      .catch(() => {})
  }
  const refresh = () => {
    searchArr.length = 0
    emit('fupdate')
  }
</script>
<template>
  <div id="table-fleet">
    <div class="refresh">
      <div class="search-box"><me-search :search="searchData" :ys="ys" :searchConArr="searchArr" @search="setSearchArr"></me-search></div>
      <el-icon @click="refresh()" class="refreshIcon">
        <RefreshLeft />
      </el-icon>
    </div>
    <div class="table-box">
      <el-table
        :data="props.data"
        style="width: 100%"
        :header-cell-style="{ background: '#fafafe', color: '#1d1d1f' }"
        :border="true"
        :default-sort="{ prop: 'creation_time', order: 'descending' }"
      >
        <el-table-column label="名称/ID" class-name="elcell">
          <template #default="scope">
            <div class="toDetails" :class="scope.row.state == 'DELETING' ? 'delete-now' : ''" @click="toDetails(scope.row.fleet_id, scope.row.name)">
              {{ scope.row.name }}
            </div>
            <el-tooltip effect="dark" :content="scope.row.fleet_id" placement="bottom">
              <div class="id-box" :class="scope.row.state == 'DELETING' ? 'delete-now' : ''">
                {{ scope.row.fleet_id }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="描述">
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.description" placement="bottom">
              <div class="idescribe">
                {{ scope.row.description }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="instance_specification" label="实例规格" show-overflow-tooltip />
        <el-table-column prop="instance_type" label="实例类型" />
        <el-table-column prop="instance_count" label="实例数量" />
        <el-table-column prop="process_count" label="进程数量" />
        <el-table-column prop="server_session_count" label="会话数量" />
        <el-table-column label="可用会话比(%)">
          <template #default="scope">
            {{
              scope.row.max_server_session_num == 0
                ? 0
                : (((scope.row.max_server_session_num - scope.row.server_session_count) / scope.row.max_server_session_num) * 100).toFixed(2)
            }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            {{ scope.row.state ? $t('fleetStatus.' + scope.row.state) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="creation_time" label="创建时间" :formatter="timeFormatUTC" sortable show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" width="130">
          <template #default="scope">
            <div class="actions-box" :class="scope.row.state == 'DELETING' ? 'delete-now' : ''">
              <div class="actions-details" @click="toDetails(scope.row.fleet_id, scope.row.name)">详情</div>
              <div class="line" v-if="userType >= 5"></div>
              <div
                class="actions-delete"
                :class="scope.row.state == 'DELETING' ? 'delete-now' : ''"
                @click="deleteFleet(scope.row.fleet_id, scope.row.name)"
                v-if="userType >= 5"
              >
                删除
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  .table-box {
    border-radius: 2px;
    margin-top: 20px;
  }
  .delete-now {
    pointer-events: none;
    color: $action-color !important;
  }
  .idescribe {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .search-box {
    width: 100%;
    border: 1px solid #e0e2e9;
  }
  #search {
    border: none;
  }
  .refresh {
    display: flex;
    justify-content: space-between;
  }
</style>
